const ServerError = require('../common/error.js')
class Model {
	constructor(httpInfo, table = "", fileds = "") {
		let time = Date.now()
		this.table = table
		this.method = httpInfo.httpMethod
		this.dbc = uniCloud.database().collection(table)
		this.time = time
		this.fileds = fileds
		if (this.method == 'POST') {
			this.data = JSON.parse(httpInfo.body)
		} else {
			this.data = httpInfo.queryStringParameters
		}
	}
	async add() {
		let data = await this.dbc.add(this.data)
		if (data.id) {
			return {
				errCode: 0,
				data: data,
				errMsg: "添加成功"
			}
		} else {
			throw new ServerError(`${this.table}添加失败`, 3001)
		}
	}
	async remove() {
		let {
			deleted
		} = await this.dbc.doc(this._id).remove()
		if (deleted) {
			return {
				errCode: 0,
				data: {
					deleted
				},
				errMsg: "删除成功"
			}
		} else {
			throw new ServerError(`${this._id}没有可删除的数据`, 3009)
		}

	}
	async update() {
		let _id = this.data._id
		delete this.data._id
		let {
			affectedDocs,
			updated
		} = await this.dbc.doc(_id).update({
			url,
			sort,
			path,
			desciption,
			status
		});
		if (updated > 0) {
			return {
				errCode: 0,
				data: upData,
				errMsg: "更新"
			}
		} else {
			throw new ServerError("未知原因更新失败", 3012)
		}

	}

	async list(page = 0, limit = 10) {
		page = parseInt(page)
		limit = parseInt(limit)
		let {
			affectedDocs,
			data
		} = await this.dbc.get();
		return {
			errCode: 0,
			data: data,
			errMsg: `${this.table}列表`
		}
	}
}

module.exports = Model
